JavaScript syntax
part 34/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Destructuring assignment
In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leaves that are to receive the substructures of the assigned value.
let a, b, c, d, e;
[a, b, c] = [3, 4, 5];
console.log(`${a},${b},${c}`); // displays: 3,4,5
e = {foo: 5, bar: 6, baz: ['Baz', 'Content']};
const arr = [];
({baz: [arr[0], arr[3]], foo: a, bar: b} = e);
console.log(`${a},${b},${arr}`); // displays: 5,6,Baz,,,Content
[a, b] = [b, a]; // swap contents of a and b
console.log(a + ',' + b); // displays: 6,5
[a, b, c] = [3, 4, 5]; // permutations
[a, b, c] = [b, c, a];
console.log(`${a},${b},${c}`); // displays: 4,5,3
Spread/rest operator
Spread syntax provides another way to destructure arrays and objects. For arrays, it indicates that the elements should be used as the parameters in a function call or the items in an array literal. For objects, it can be used for merging objects together or overriding properties.
In other words, "..." transforms "[...foo]" into "[foo[0], foo[1], foo[2]]", and "this.bar(...foo);" into "this.bar(foo[0], foo[1], foo[2]);", and "{ ...bar }" into { prop: bar.prop, prop2: bar.prop2 }.
const a = [1, 2, 3, 4];
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────